Medium
Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
Example:
1 | X X X X |
After running your function, the board should be:
1 | X X X X |
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically
首先这题让我想到了数海岛那道题,同样都需要找联通的图案,所以很自然就想到需要dfs来进行联通的遍历,但是由于dfs必然会重复遍历一些点,所以就需要visit
来记录哪些点已经遍历过了。
首先,根据观察可以发现,只有边上的O
或者是和边上O
连起来的O
才不会被变成X
。所以我的思路很简单,就是遍历除边上以外的O
,再通过dfs查找他是否于边上的O
连着。但是时间复杂度一想就很高。
然后我想到利用visit
在dfs的过程中就标记好联通的O
然后一起改成X
,这部分代码暂定
最后看了别人的思路。感觉很有道理。
解法一是从当前节点做 DFS
,然后看它是否能到达边界的 O
。那么我们能不能把思路逆转过来呢?从边界的 O
做 DFS
,然后把遇到的 O
都标记一下,这些 O
就是可以连通到边界的。然后把边界的所有的 O
都做一次 DFS
,把 DFS
过程的中的 O
做一下标记。最后我们只需要遍历节点,把没有标记过的 O
改成 X
就可以了。标记的话,我们可以用一个 visited
二维数组,把访问过的置为 true
。
1 | class Solution: |
同样参考了他的优化改良思路。直接在board上记录,不需要visit
1 | class Solution: |
UnionFind 查并集
查并集是什么,可以点这里。虽然查并集用在这题效率并没有高多少,但是这也不失为一种简单,且容易想到的解题思路。
查并集,算法如其名,两大功能就是查找(found)和合并(Union)。
1 | class UnionFound: |